package edu.ccut.saturn.tag.freemark;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class FreemarkerUtils {
	
	private static Configuration freemarkerCfg;
	
	static {
		init();
	}
	
	private FreemarkerUtils(){
		
	}
	
	private static void init() {
		freemarkerCfg = new Configuration();
		
		List<ClassTemplateLoader> loaders = new ArrayList<ClassTemplateLoader>();
		loaders.add(new ClassTemplateLoader(FreemarkerUtils.class, "/"));
		
		freemarkerCfg.setTemplateLoader(new MultiTemplateLoader(
				(TemplateLoader[]) loaders.toArray(new TemplateLoader[loaders
						.size()])));
		
		freemarkerCfg.setDefaultEncoding("UTF-8");
	}

	/**
	 * Write template information to the writer
	 * 
	 * @param templateFileName
	 * @param propMap
	 * @param writer
	 * @return
	 */
	public static boolean writeTemplate(String templateFileName, Map<String, ?> propMap, Writer writer) {
		try {
			Template template = freemarkerCfg.getTemplate(templateFileName);
			
			template.setEncoding("UTF-8");
			
			template.process(propMap, writer,ObjectWrapper.BEANS_WRAPPER);
			
			StringWriter tempWriter = new StringWriter();
			BufferedWriter bw = new BufferedWriter(tempWriter);
			template.process(propMap, bw,ObjectWrapper.BEANS_WRAPPER);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return true;
	}
	
	/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {
		Map propMap = new HashMap();
		propMap.put("aaa", "你也好");
		
		StringWriter tempWriter = new StringWriter();
		BufferedWriter bw = new BufferedWriter(tempWriter);
		
		FreemarkerUtils.writeTemplate("template/bl.ftl", propMap, bw);
		
		bw.close();
	}


}
